import React, { useEffect, useRef, useState } from "react";
import { Modal,Card,Spin, Empty} from 'antd';
import classNames from "classnames";
import {queryByBookId,getBookContentAll} from 'api/index'
import $ from 'jquery'
import './turn'
const { Meta } = Card;


const PreviewAudio = (props) => {
  const {isModalVisible, setIsModalVisible,id} = props

  const [time,setTime] = useState(0) // 记录音频播放进度
  const [audioUrl,setAudioUrl] = useState('')//音频地址
  const [imgUrl,setImgUrl] = useState('')//音频地址
  const [bookInfo,setBookInfo] = useState({}) //书的基本信息
  const [content,setContent] = useState([]) //所有数据
  const [spinning,setSpinning] = useState(false) //打开页面前的加载
  const [pageCount,setageCount] = useState(0) //记录当前播放的面
  const [imgInfo,setimgInfo] = useState({
    xWidth:0,
    yHeight:0,
  }) //比例
  const audio = useRef(null) //音频播放
  const img = useRef(null) // 用来获取图片宽高
  const timeOut = useRef(null) 
  const book = useRef(null) 

  useEffect(()=>{
       if(!id||!isModalVisible) return

       setSpinning(true)

        const getData = async() => {
        const res = await queryByBookId(id.slice(0,id.indexOf('?')))

        if(!res.result.contentFlows||!res.result.contentFlows.length) return //没有内容

        setImgUrl(res.result.contentFlows[0].pictureUrl) // 存在内容情况

        book.current=res.result

        const res1 = await getBookContentAll(id.slice(0,id.indexOf('?')))
        
       let arr = sortArr(res1.result, 'flowBookContentId')

  
        setBookInfo(res.result.contentFlows||res.request.contentFlows)

        const data = []

        res.result.contentFlows.map(i => i.id).forEach((item, index) => {
          data.push(arr.filter(i => i[0].flowBookContentId === item)[0])
        })

        arr = data.map(i => i || [{}])
        
        arr.forEach((i, index) => {
          i.forEach(x => {
            x.pictureUrl = res.result.contentFlows[index].pictureUrl
            x.audioUrl = res.result.contentFlows[index].audioUrl
            x.captionUrl = res.result.contentFlows[index].captionUrl
          })
        })

        setContent(arr) //保存所有数据

     // 初始化翻页
       timeOut.current = setTimeout(()=>{
        if(img.current){
            $('.modal-full .flipbook').turn({
              width: 1000,
              height:img.current.naturalHeight / (img.current.naturalWidth / 500),
              autoCenter: true
           })

           setimgInfo({
            xWidth:img.current.naturalWidth,
            yHeight:img.current.naturalHeight,
           })

            
        //   监听翻页事件
           $('.modal-full .flipbook').bind("turned",function(event,page,view){
               console.log(view,'view');
            setTime(0)
            setageCount(view[0])//当前面
             
            // 如果当前是第一面 
            if(view[0]===0){
              if(!res.result.contentFlows[0].audioUrl&&arr.length) { //不存在音频
                $('.modal-full .flipbook').turn("next")
              } else {
                setAudioUrl(res.result.contentFlows[0].audioUrl)
                audio.current&&audio.current.load()
                audio.current&&(audio.current.oncanplay = async() => {
                  audio.current.play()
                 })
              }
            }
            // 当此页面不是第一页
            if(res.result.contentFlows[view[0]-1]&&view[0]!==0){
                if(res.result.contentFlows[view[0]-1].audioUrl){ //存在音频
                    setAudioUrl(res.result.contentFlows[view[0]-1].audioUrl)
                    audio.current&&audio.current.load()
                    audio.current&&(audio.current.oncanplay = async() => {
                      audio.current.play()
                     })
                } else { // 不存在音频
                    if(res.result.contentFlows[view[0]]&&res.result.contentFlows[view[0]].audioUrl) {
                        setAudioUrl(res.result.contentFlows[view[0]].audioUrl)
                        audio.current&&audio.current.load()
                        audio.current&&(audio.current.oncanplay = async() => {
                          setageCount(i=>i+1)//当前面
                          audio.current.play()
                      })
                    }
                }
            }
           })
           /**
            * content [[{},{}],[{}],[{}]]
            * bg 开始时间
            * ed 结束时间
            * audioUrl 音频 （存在为空但是有字幕的可能）
            * pictureUrl 图片 
            * captionUrl 字幕
            * captionUrl 字幕
            * onebest 句子
            * captionUrl 字幕
            * wordFlows 单词 x x轴坐标 y y轴坐标  行高 宽度 高度 字体大小 wordBg wordEd
            */
   
           if(arr[0][0].audioUrl) {
               // 封面有音频的情况
             setAudioUrl(arr[0][0].audioUrl)
               //开始播放音频   
               audio.current&&audio.current.load()
               audio.current&&(audio.current.oncanplay = async() => {
               audio.current.play()
             })
           } else {
              //封面无音频 跳转下一页
              arr.length>0&&$('.modal-full .flipbook').turn("next")
           }
   
           setSpinning(false)
         }
      },500)
  }

       getData()

       return ()=> {
        setTime(0)
        setBookInfo({})
        setContent([])
        setageCount(0)
        setAudioUrl('')
        setimgInfo({
            xWidth:0,
            yHeight:0,
        })
        clearTimeout(timeOut.current)
       }
  },[isModalVisible]) // eslint-disable-line react-hooks/exhaustive-deps

  // 排序
  const sortArr = (arr, str) => {
    var _arr = []
    var _t = []
    // 临时的变量
    var _tmp

    // 按照特定的参数将数组排序将具有相同值得排在一起
    arr = arr.sort(function(a, b) {
      var s = a[str]
      var t = b[str]

      return s < t ? -1 : 1
    })

    if (arr.length) {
      _tmp = arr[0][str]
    }
    // console.log( arr );
    // 将相同类别的对象添加到统一个数组
    for (var i in arr) {
      console.log(_tmp)
      if (arr[i][str] === _tmp) {
        console.log(_tmp)
        _t.push(arr[i])
      } else {
        _tmp = arr[i][str]
        _arr.push(_t)
        _t = [arr[i]]
      }
    }
    // 将最后的内容推出新数组
    _arr.push(_t)
    return _arr
  }

  // 关闭弹框
  const onCancel = () => {
    if(audio.current){
      audio.current.pause()
    }

    setIsModalVisible(false);
  };
//   音频结束
const onEnded = () => {
    setTime(0)

    if(pageCount===0){
        $('.modal-full .flipbook').turn("next")
        return
      }
  
     if(pageCount%2===0){

       // 并且下一页存在数据 但是不存在音频
       if(bookInfo[pageCount]&&!bookInfo[pageCount].audioUrl) {
           if(bookInfo.length===pageCount+1) {
             return
           }
          $('.modal-full .flipbook').turn("next")

       }
       // 下一页存在数据存在音频
       if(bookInfo[pageCount]&&bookInfo[pageCount].audioUrl) {
           setAudioUrl(bookInfo[pageCount].audioUrl)
            audio.current&&audio.current.load()
            audio.current&&(
              audio.current.oncanplay = async() => {
                audio.current.play()
               }
            )
            audio.current&&setageCount(i=>i+1)//当前面
        }
      } else {
      //    如果是单页 并且下一页有数据
         bookInfo.length>=pageCount+1&&$('.modal-full .flipbook').turn("next")
      }

       //  下一页不存在 返回首页
      if(!bookInfo[pageCount]){
         console.log('下一页不存在 返回首页');
        return
      } 
}
// 音频播放
const onTimeUpdate = (e) => {
    setTime(e.target.currentTime*1000)
}



  return   <Modal destroyOnClose wrapClassName="modal-full book-background"  visible={isModalVisible}  onCancel={onCancel}>

           <div className="flipbook">
              
              {
                content.length?content.map((i,j)=>{
                  return <div key={j} className={classNames(pageCount % 2 === 0?'wordLeft':'wordRight')}>
                         {
                         spinning?(j===0? <Spin tip="正在获取数据中..." className="book-spin" size="large" />:''):(
                           <>
                            <img src={i[0].pictureUrl} alt=""/>
                           </>
                          )
                         }
                  </div>
                }):<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              }
         </div>
      
           {/* 非首页 */}
           {pageCount!==0&&content[pageCount-1]&&content[pageCount-1][0].captionUrl?content[pageCount-1].map(y=>y.wordFlows).flat().map(x=>{
              return x.width?<span key={x.id} className="word" style={{width:(x.width-x.x) * 0.01 * 500 + 'px',lineHeight:(x.height-x.y) * 0.01 * imgInfo.yHeight + 'px',height:(x.height-x.y) * 0.01 * imgInfo.yHeight + 'px',fontSize:(x.height-x.y) * 0.01 * imgInfo.yHeight / 2 - 2+ 'px',position:'absolute',left: pageCount % 2 === 0?x.x *  5 +320 + 24 + 'px':x.x*5 + 844 + 'px',top:500 / imgInfo.xWidth * imgInfo.yHeight - 500 / imgInfo.xWidth * imgInfo.yHeight * x.y * 0.01 - (x.height-x.y) * 0.01 * imgInfo.yHeight + 86 + 50 + 'px',zIndex:999}}>
              {time>x.wordBg&&time<x.wordEd?x.wordsName:''}
           </span>:<span key={x.id}className="word"  style={{position:'absolute',left:pageCount % 2 === 0?'520px':'1020px',fontSize:'20px',top:imgInfo.yHeight + 50 + 'px'}} >{time>x.wordBg&&time<x.wordEd?x.wordsName:''}</span>
            }):''}

             {pageCount!==0&&content[pageCount]&&(!content[pageCount][0].audioUrl&&content[pageCount][0].captionUrl)?content[pageCount].map(y=>y.wordFlows).flat().map(x=>{
              return x.width?<span key={x.id} className="word" style={{width:(x.width-x.x) * 0.01 * 500 + 'px',lineHeight:(x.height-x.y) * 0.01 * imgInfo.yHeight + 'px',height:(x.height-x.y) * 0.01 * imgInfo.yHeight + 'px',fontSize:(x.height-x.y) * 0.01 * imgInfo.yHeight / 2 - 2+ 'px',position:'absolute',left: x.x*5 + 320 + 524 + 'px',top:500 / imgInfo.xWidth * imgInfo.yHeight - 500 / imgInfo.xWidth * imgInfo.yHeight * x.y * 0.01 - (x.height-x.y) * 0.01 * imgInfo.yHeight + 86 +50 + 'px',zIndex:999}}>
              {time>x.wordBg&&time<x.wordEd?x.wordsName:''}
           </span>:<span key={x.id}className="word"  style={{position:'absolute',left:pageCount % 2 === 0?'520px':'1020px',fontSize:'20px',top:imgInfo.yHeight + 50 + 'px'}} >{time>x.wordBg&&time<x.wordEd?x.wordsName:''}</span>
            }):''}
             
             {/* 首页 */}
           {pageCount===0&&content[0]&&content[0][0].captionUrl?content[0].map(y=>y.wordFlows).flat().map(x=>{
              return x.width?<span key={x.id} className="word" style={{width:(x.width-x.x) * 0.01 * 500 + 'px',lineHeight:(x.height-x.y) * 0.01 * imgInfo.yHeight + 'px',height:(x.height-x.y) * 0.01 * imgInfo.yHeight + 'px',fontSize:(x.height-x.y) * 0.01 * imgInfo.yHeight / 2 - 2+ 'px',position:'absolute',left: x.x *  5 + 320 + 274 + 'px',top:500 / imgInfo.xWidth * imgInfo.yHeight - 500 / imgInfo.xWidth * imgInfo.yHeight * x.y * 0.01 - (x.height-x.y) * 0.01 * imgInfo.yHeight + 86 +50 + 'px',zIndex:999}}>
              {time>x.wordBg&&time<x.wordEd?x.wordsName:''}
           </span>:<span key={x.id} className="word"  style={{position:'absolute',left:'820px',fontSize:'20px',top: imgInfo.yHeight + 50 + 'px'}} >{time>x.wordBg&&time<x.wordEd?x.wordsName:''}</span>
          }):''}
             

      <div className="onebest">
          {/* 第一页 */}
          {pageCount===0?content[0]?content[0].map(i=>{
            return <span  key={i.onebest}>{i.ed>time&&i.bg<time?i.onebest:''}</span>
          }):'':''}
          {/* 不是第一页 */}
          {pageCount!==0?content[pageCount-1]?content[pageCount-1].map(i=>{
            return <span key={i.onebest}>{i.ed>time&&i.bg<time?i.onebest:''}</span>
          }):'':''}
         {/* 引用上一个音频 */}
         {pageCount!==0?content[pageCount]&&(!content[pageCount][0].audioUrl&&content[pageCount][0].captionUrl)?content[pageCount].map(i=>{
            return <span key={i.onebest}>{i.ed>time&&i.bg<time?i.onebest:''}</span>
          }):'':''}
      </div>

     {
        content.length?<div className="book-info">
        <h1>绘本预览</h1>
       <Card
        className=""
         hoverable
         style={{ width: 300 }}
         cover={<img alt="example" src={book.current?book.current.pictureUrl:''} />}
       >
         <div className="book-info-title">
           {book.current?book.current.bookName:''}
         </div>
         <div className="book-info-text">
           <div>
             <p>xx 个</p>
             <p>单词</p>
           </div>
           <div>
             <p>{book.current?(book.current.lexileValue?book.current.lexileValue:'无'):'无'}</p>
             <p>蓝思值</p>
           </div>
           <div>
             <p>{pageCount / 2 + '/' + (content.length - 1) / 2 }</p>
             <p>当前页</p>
           </div>
         </div>
       </Card>
  </div>:''
     }
      
      
      <img src={imgUrl} ref={img} alt="" style={{width:'1px'}}/>
      <audio onTimeUpdate={onTimeUpdate} ref={audio} src={audioUrl} onEnded={onEnded}></audio>
   </Modal>

}
export default PreviewAudio